<template>
  <el-card class="box-card" shadow="never" style="min-width: 1120px">
    <el-row>
      <el-col :span="1" style="margin: 0">
        <div style="margin-top: 8px;">
          <el-text class="mx--1" style="font-weight: bold;">厂商</el-text>
        </div>
      </el-col>
      <el-col :span="23">
        <el-button-group>
          <el-button class="btn" :type="state.selectIdx===item.id? 'primary':''" v-for="item in state.group"
                     :key="item.id" @click="doGroupSearch(item.id)">{{ item.title }}
          </el-button>
        </el-button-group>
      </el-col>

    </el-row>
    <div style="margin-top: 10px;">
      <el-form ref="searchFormRef" :inline="true" :model="state.searchForm">
        <el-form-item label="平台名称" prop="title">
          <el-input style="width: 200px;" v-model="state.searchForm.title" placeholder="平台名称" clearable/>
        </el-form-item>
        <el-form-item label="网址" prop="url">
          <el-input style="width: 200px;" v-model="state.searchForm.url" placeholder="网址" clearable/>
        </el-form-item>
        <el-form-item label="区域" prop="region">
          <el-select style="width: 130px;" v-model="state.searchForm.region" placeholder="区域" clearable>
            <el-option
                v-for="item in state.searchForm.options.region"
                :key="item.id"
                :label="item.label"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="date_range">
          <el-date-picker
              v-model="state.searchForm.date_range"
              type="daterange"
              start-placeholder="起始"
              end-placeholder="结束"
              :shortcuts="shortcuts"
              style="width: 200px;"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch">搜 索</el-button>
          <el-button type="primary" @click="doResetSearchForm" plain>重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row>
      <el-button type="primary" v-per2="['cloudplatform-list','post']" @click="doAddPlatform">添加平台</el-button>
    </el-row>
    <div style="margin-top:5px">
      <el-row>
        <el-table :data="state.tableData"
                  border
                  style="width: 100%"
                  stripe
                  :tooltip-formatter="tableRowFormatter"
                  v-loading="state.isLoading"
                  v-per2="['cloudplatform-list','get']">
          <el-table-column prop="title" label="名称" align="center"/>
          <el-table-column prop="vendor_title" label="厂商" align="center"/>
          <el-table-column prop="platform_type_text" label="平台类型" align="center"/>
          <el-table-column prop="region_text" label="区域" align="center"/>
          <el-table-column
              prop="url"
              show-overflow-tooltip
              :tooltip-formatter="withVNode"
              label="网址"/>
          <el-table-column prop="is_innovation" label="是否信创" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.is_innovation" size="large" effect="dark" type="success">是</el-tag>
              <el-tag v-else type="info">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="api_user" label="接口用户" align="center"/>
          <el-table-column prop="operator_display" width="130px" label="运维人员" align="center">
            <template #default="scope">
              <el-tag style="margin-right: 5px" type="primary" v-for="item in scope.row.operator_display"
                      :key="item.id">
                {{ item.username_str }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="creator_display" label="创建人" align="center"/>
          <el-table-column prop="ctime" label="创建日期" align="center"/>
          <el-table-column prop="api_status" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.api_status===3" type="info" effect="dark" size="large" round :hit="true">
                {{ scope.row.api_status_text }}
              </el-tag>
              <el-tag v-else-if="scope.row.api_status===2" type="warning" effect="dark" size="large" round :hit="true">
                {{ scope.row.api_status_text }}
              </el-tag>
              <el-tag v-else type="success" effect="dark" size="large" round :hit="true">
                {{ scope.row.api_status_text }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="desc" label="平台描述" show-overflow-tooltip  align="center"/>
          <el-table-column v-per2="['userinfo-reset-password','put']" prop="is_super" label="指派运维人员" align="center">
            <template #default="scope">
              <el-button v-per2="['cloudplatform-operator','put']" type="primary"
                         class="card-small-btn" size="small"
                         @click="doAssignPlatform(scope.row,scope.$index)">指派
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
              v-if="hasButton([{'name':'cloudplatform-detail','method':'delete'},{'name':'cloudplatform-detail','method':'put'}])"
              prop="username" label="操作">
            <template #default="scope">
              <el-popconfirm
                  cancel-button-type="danger"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="confirmUserDelete(scope.row)"
                  title="确认删除吗?">
                <template #reference>
                  <el-button v-per2="['cloudplatform-detail','delete']" type="danger"
                             icon="Delete" size="small"
                             class="card-small-btn">
                  </el-button>
                </template>
              </el-popconfirm>
              <el-button v-per2="['cloudplatform-detail','put']" type="success" icon="Edit"
                         class="card-small-btn" size="small"
                         @click="doEditPlatform(scope.row,scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <MinePager v-per2="['cloudplatform-list','get']" :pager="state.pager"/>
      </el-row>
    </div>
  </el-card>
  <MineDialog :obj="state.dialog"></MineDialog>
  <el-dialog
      v-model="state.transferDiaglog.visible"
      title="指派运维人员"
      width="50%"
      :show-close="false"
      style="padding: 0"
      :props="{key: 'id',label: 'username'}"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="header">
        <span>指派运维人员</span>
        <el-link @click="close" :underline="false">
          <el-icon style="color: white">
            <Close/>
          </el-icon>
        </el-link>
      </div>
    </template>
    <el-row style="justify-content: center">
      <el-transfer v-model="state.transferDiaglog.value"
                   :data="state.transferDiaglog.data"
                   filterable
                   :titles="['用户列表', '已选用户列表']"
                   @change="handleChange"
                   :props="{key:'id',label:'username'}"
      />
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-row :gutter="50" justify="center" align="middle" style="height: 80px">
          <el-form-item>
            <el-button @click="submitAssign" type="primary" style="width: 150px;height: 40px">提 交</el-button>
            <el-button @click="state.transferDiaglog.visible = false" type="primary" style="width: 150px;height: 40px">取
              消
            </el-button>
          </el-form-item>
        </el-row>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

import {h, onMounted, reactive, ref} from "vue";
import _axios from "@/plugin/axios.js";
import {ElLink, ElMessage} from "element-plus";
import MineDialog from "@/components/DialogDouble.vue";
import MinePager from "@/components/MinePager.vue";
import {clearFormError, validateFormError} from "@/plugin/form.js";
import {hasButton, hasPermission2} from "@/stores/permission.js";

const searchFormRef = ref(null)
const shortcuts = [
  {
    text: '一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
const state = reactive({
  selectIdx: -1,
  group: [
    {id: -1, title: '全部'}
  ],
  isLoading: false,
  tableData: [],
  pager: {
    currentPage: 1,
    totalCount: 0,
    perPageSize: Number(localStorage.getItem("pageSize")) || 10,
    handleSizeChange: handleSizeChange,
    handleChangePage: handleChangePage
  },
  editId: -1,
  editIndex: -1,
  dialog: {
    visible: false,
    title: "",
    form: {
      title: "",
      vendor: "",
      is_innovation: false,
      platform_type: 1,
      region: 1,
      location: "",
      url: "",
      api_user: "",
      password: "",
      desc: ""
    },
    errors: {
      title: "",
      vendor: "",
      is_innovation: "",
      platform_type: "",
      region: "",
      location: "",
      url: "",
      api_user: "",
      password: "",
      desc: ""
    },
    fields: [
      {name: 'title', label: '云平台名称', wiget: 'input'},
      {name: 'vendor', label: '厂商', wiget: 'select'},
      {name: 'location', label: '位置', wiget: 'input'},
      {name: 'url', label: '网址', wiget: 'input'},
      {name: 'api_user', label: '接口用户', wiget: 'input'},
      {name: 'password', label: '密码', wiget: 'password'},
      {name: 'is_innovation', label: '是否信创', wiget: 'switch'},
      {name: 'platform_type', label: '平台类型', wiget: 'radio'},
      {name: 'region', label: '区域', wiget: 'radio'},
      {name: 'desc', label: '平台描述', wiget: 'textarea'},
    ],
    options: {
      vendor: [],
      platform_type:
          [
            {id: 1, title: '超融合'},
            {id: 2, title: '云平台'}
          ],
      region:
          [
            {id: 1, title: '内部服务网'},
            {id: 2, title: '外部服务网'}
          ]
    },
    doSubmit: doSubmit
  },
  transferDiaglog: {
    visible: false,
    value: [],
    data: [],
    defaultData: []
  },
  searchForm: {
    title: "",
    url: "",
    date_range: "",
    region: "",
    options: {
      region: [
        {id: 1, label: "内部服务网"},
        {id: 2, label: "外部服务网"},
      ]
    }
  }
})

onMounted(() => {
  initTableData()
  initVendor()
})


function initVendor() {
  _axios.get('/api/web/cloud_platform/vendor/').then((res) => {
    if (res.data.code === 0) {
      state.dialog.options.vendor = res.data.data
      state.group.push(...res.data.data)

    }
  })
}

function initOperator() {
  _axios.get(`/api/web/cloud_platform/${state.editId}/operator/list/`).then((res) => {
    if (res.data.code === 0) {
      state.transferDiaglog.data = res.data.data['users'];
      state.transferDiaglog.value = res.data.data['operators'];
    }
  })
}

function initTableData() {
  if (!hasPermission2("cloudplatform-list", "get")) {
    return
  }
  state.isLoading = true
  let search_params = {page: state.pager.currentPage, page_size: state.pager.perPageSize}
  if (state.selectIdx !== -1) {
    search_params['vendor'] = state.selectIdx
  }
  for (let key in state.searchForm) {
    let value = state.searchForm[key]
    if (key === "options") {
      continue
    }
    if (!value) {
      continue
    }
    if (key === "date_range") {
      search_params["start_date"] = value[0]
      search_params["end_date"] = value[1]
    } else {
      search_params[key] = value
    }
  }
  _axios.get("/api/web/cloud_platform/", {params: search_params}).then((res) => {
    if (res.data.code === 0) {
      state.tableData = res.data.data.data;
      state.pager.totalCount = res.data.data.totalCount;
      state.pager.perPageSize = res.data.data.perPageSize
      state.isLoading = false
    }
  })
}

function doSearch() {
  state.pager.currentPage = 1
  initTableData()
}

function handleChangePage(page) {
  state.pager.currentPage = page
  initTableData()
}

function handleSizeChange(page_size) {
  localStorage.setItem("pageSize", page_size)
  state.pager.perPageSize = page_size
  state.pager.currentPage = 1
  initTableData()
}

function doAddPlatform() {
  state.dialog.visible = true
  state.dialog.title = '添加云平台'
  state.editId = -1
  state.editIndex = -1
  clearFormError(state.dialog.errors)
  state.dialog.form = {
    title: "",
    vendor: "",
    is_innovation: false,
    platform_type: 1,
    region: 1,
    location: "",
    url: "",
    api_user: "",
    password: "",
    desc: ""
  }
}

function doEditPlatform(row, index) {
  clearFormError(state.dialog.errors)
  state.dialog.visible = true
  state.dialog.title = '编辑平台'
  state.editId = row.id
  state.editIndex = index
  let platformDict = state.tableData[index]
  state.dialog.form = {
    title: platformDict.title,
    vendor: platformDict.vendor,
    is_innovation: platformDict.is_innovation,
    platform_type: platformDict.platform_type,
    region: platformDict.region,
    location: platformDict.location,
    url: platformDict.url,
    api_user: platformDict.api_user,
    password: platformDict.password,
    desc: platformDict.desc
  }
}

function doAssignPlatform(row, index) {
  state.transferDiaglog.visible = true
  state.editId = row.id
  state.editIndex = index
  initOperator()

}

function submitAssign() {
  _axios.put(`/api/web/cloud_platform/${state.editId}/operator/`, state.transferDiaglog.value).then((res) => {
    if (res.data.code === 0) {
      console.log(res.data.data["operators"])
      state.tableData[state.editIndex]["operator_display"] = res.data.data["operators"]
      state.editId = -1
      state.editIndex = -1
      state.transferDiaglog.visible = false
    } else {
      ElMessage.error("指派失败")
    }
  })

}

function handleChange(value, direction, moveKeys) {
  console.log(value, direction, moveKeys);
}

function confirmUserDelete(row) {
  _axios.delete(`/api/web/user/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      state.tableData = state.tableData.filter((item) => {
        return row.id !== item.id
      })
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  })
}


function doSubmit() {
  clearFormError(state.dialog.errors)
  if (state.editId > 0) {
    _axios.put(`/api/web/cloud_platform/${state.editId}/`, state.dialog.form).then((res) => {
      if (res.data.code === 0) {
        state.tableData[state.editIndex] = res.data.data
        state.editId = -1
        state.editIndex = -1
        state.dialog.visible = false
      } else if (res.data.code === 2001) {
        validateFormError(state.dialog.errors, res.data.detail)
      } else {
        ElMessage.error("编辑失败")
      }
    })
  } else {
    _axios.post('/api/web/cloud_platform/', state.dialog.form).then((res) => {
      if (res.data.code === 0) {
        state.dialog.visible = false
        initTableData()
      } else if (res.data.code === 2001) {
        validateFormError(state.dialog.errors, res.data.detail)
      } else {
        ElMessage.error("添加失败")
      }
    })
  }
}


function doResetSearchForm() {
  searchFormRef.value.resetFields()
}

function doGroupSearch(idx) {
  state.selectIdx = idx
  initTableData()
}

const tableRowClassName = ({row, rowIndex}) => {
  if (rowIndex % 2 == 0) {
    return 'warning-row'
  } else if (rowIndex % 2 === 1) {
    return 'success-row'
  }
}

const tableRowFormatter = (data) => {
  return `${data.cellValue}: table formatter`
}
const withVNode = (data) => {
  return h(ElLink, {type: 'primary', href: data.cellValue05, target: "_blank"}, () =>
      h('span', null, data.cellValue)
  )
}

</script>

<style scoped>
.box-card .btn {
  margin: 5px 5px;
}

.header {
  color: #FFFFFF;
  height: 48px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: rgb(51.2, 126.4, 204);
}

.el-transfer {
  --el-transfer-border-color: var(--el-border-color-lighter);
  --el-transfer-border-radius: var(--el-border-radius-base);
  --el-transfer-panel-width: 300px;
  --el-transfer-panel-header-height: 40px;
  --el-transfer-panel-header-bg-color: var(--el-fill-color-light);
  --el-transfer-panel-footer-height: 40px;
  --el-transfer-panel-body-height: 50vh;
  --el-transfer-item-height: 30px;
  --el-transfer-filter-height: 32px;
  font-size: var(--el-font-size-base);
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

::v-deep(.el-popper) {
  max-width: 350px;
  word-break: break-all;
}


</style>